﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace MenusHunter.WinRT.Core
{
    public static class HttpRequest
    {
        public static async Task<string> GetJsonAsync(string url)
        {
            WebResponse response = null;
            try
            {
                HttpWebRequest request = CreateWebRequest(url, "GET", "text/json; encoding=utf-8");

                response =
                    await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
                var responseStream = response.GetResponseStream();
                using (var reader = new StreamReader(responseStream))
                {
                    return await reader.ReadToEndAsync();
                }
            }
            finally
            {
                if (response != null) response.Dispose();
            }
        }

        public static async Task<string> PostAsync(string url, object parameter = null)
        {
            var client = new HttpClient();
           
            StringContent data = null;
            if(parameter!=null)
            {
                var dataStr = JsonConvert.SerializeObject(parameter);
                data = new StringContent(dataStr, Encoding.UTF8, "application/json");        
            }
           var response =  await client.PostAsync(url, data);
            var contentString = await response.Content.ReadAsStringAsync();
            return contentString;
        }

        private static HttpWebRequest CreateWebRequest(string url, string method, string contentType)
        {
            var request = WebRequest.CreateHttp(url);
            request.Method = method;
            request.ContentType = contentType;
            return request;
        }
    }
}